<template>
  <div class="app-container">
    <!-- <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages> -->
    <Table v-bind="table" :allId="allId" :isAllCheck="isAllCheck" ref="tableRef" @goAddPackingRecord="goAddPackingRecord" @pageChange="onTablePageChange" @showInfo="showInfo"
      @downloadFile="downloadFile" @activEdit="activEdit" @showPackingRecord="showPackingRecord" @drawerPackingOpen="drawerPackingOpen" @endPacking="endPacking"  @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>
     <!-- 添加提箱记录 -->
    <el-drawer v-model="param.drawerPackingRecord"  @close="resetForm" :with-header="false" size="800px">
      <span class="_before">添加提箱记录</span>
      <el-form :model="param" ref="packingRecordFormRef" :rules="packingRecordFormRules" label-width="100px"
        style="margin-top: 20px;">
        <el-form-item :label-width="'35px'">
          <div style=" color:#606266;font-weight: 600" class="_asterisk">选择订单</div>
          <el-table ref="singleTableRef" :data="param.orderList" :row-key="orderId" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="30"></el-table-column>
            <el-table-column prop="orderNo" width="200" label="订单号" align="center"></el-table-column>
            <el-table-column prop="orderTime" width="200" label="下单日期" align="center"></el-table-column>
            <el-table-column prop="packedQuantity" align="center">
              <template #header>
                <el-tooltip content="订单关联的提箱单已提箱量" effect="dark" placement="top">
                  <el-button link>
                    已提箱量
                    <el-icon class="el-icon--right">
                      <QuestionFilled />
                    </el-icon>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="waitPackingQuantity" align="center" width="110">
              <template #header>
                <el-tooltip content="订单关联的提箱单未提箱量" effect="dark" placement="top">
                  <el-button link>
                    未提箱量
                    <el-icon class="el-icon--right">
                      <QuestionFilled />
                    </el-icon>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <div style="display: flex;justify-content: space-between;">
        <el-form-item label="提箱单号">{{ rowData.packingNo }}</el-form-item>
          <el-form-item label="箱型">{{ boxTypeFilter(rowData.boxType) }} </el-form-item>
        <el-form-item label="箱况">
          <template v-if="rowData.boxCondition == 20">
            <el-select  v-model="param.boxCondition" clearable  placeholder="选择箱况" style="width: 200px;">
                <el-option label="适货" value="15"/>
                <el-option label="次新" value="10"/>
            </el-select>
          </template>
          <template v-else>
            <span>{{ boxConditionFilter(rowData.boxCondition) }}</span>
          </template>
        </el-form-item>
        </div>  

        <el-form-item label="堆场名称">{{ rowData.yardName }} </el-form-item>
          <el-form-item label="成本价" prop="rentInPrice" v-if="!isAgent">
          <div class="input-sel" style="display: flex;">
                  <el-select v-model="param.rentInCurrency" style="width: 60px" placeholder="请选择">
                          <el-option
                              v-for="item in feeCurrencyList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                          />
                        </el-select>
                  <el-input :formatter="formatterNumberKo" :parser="formatterNumberKo" v-model="param.rentInPrice" style="width: 130px" placeholder="请输入成本价" maxlength="20" />
                </div>
        </el-form-item>
        <el-form-item label="提箱日期" prop="packingDate">
          <el-date-picker v-model="param.packingDate" type="date" :default-value="new Date()" />
        </el-form-item>
        <el-form-item label="箱号" prop="containerNo">
          <template v-if="rowData.containerClassify == 5"> <!--自有箱-->
            <el-input v-model="param.containerNo" clearable @change="inStock"></el-input>
          </template>
          <template v-else> <!--外调箱-->
            <el-input v-model="param.containerNo" clearable></el-input>
          </template>
        </el-form-item>
        
        <el-form-item label="车牌号" prop="plateNumber">
          <el-input v-model="param.plateNumber"></el-input>
        </el-form-item>
        <el-form-item :label-width="'25px'">
          <div>提箱照片</div>
          <ImgUpload ref="packingRef" v-if="param.drawerPackingRecord" :displayType="2" :fileSize="3" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAddPackingRecord" style="margin-top: 20px;">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
      <!-- 开提箱单 -->
    <el-drawer v-model="param.drawerPacking" :show-close="false" :destroy-on-close="true" :with-header="false" size="40%">
      <span class="_before">开提箱单</span>
      <OwnBox v-if="param.packingType == '5' " ref="ownboxRef" :packingInfo="param.buildData"  :orderType="param.orderType" @closeDialog="closeDialog"></OwnBox> <!--自有箱-->
      <ExternalBox v-if="param.packingType == '15'" ref="externboxlRef" :packingInfo="param.buildData" :orderType="param.orderType" @closeDialog="closeDialog"></ExternalBox><!--外调箱-->
    </el-drawer>
    <!-- 提箱记录 -->
    <el-drawer v-model="param.drawer3" :with-header="false">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>提箱记录
      </span>
      <div style="float: right;margin-top: 60px;">
        <span>应提箱量：{{ rowData.totalQuantity }} 个</span> &nbsp;
        <span>实提箱量：{{ rowData.packedQuantity }} 个</span>
      </div>
      <el-table :data="packingRecord" style="margin-top: 100px;">
        <el-table-column prop="containerNo" width="150" label="箱号" />
        <el-table-column prop="boxType" label="箱型" />
        <el-table-column prop="boxCondition" label="箱况" />
        <el-table-column prop="packingDate" width="150" label="提箱日期" />
      </el-table>
    </el-drawer>

    <!-- 提箱单详情 -->
    <el-drawer v-model="param.drawer2" @close="infoClose" :with-header="false" size="40%">
      <span class="_before" v-if="typeDrawer==1">提箱单详情</span>
      <span class="_before" v-else-if="typeDrawer==2">提箱单编辑</span>
      <div v-if="packingInfo.containerClassify == 5">
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">租箱企业：</el-col>
          <el-col :span="19">{{ packingInfo.companyName }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">提箱单号：</el-col>
          <el-col :span="19">{{ packingInfo.packingNo }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">提箱单类型：</el-col>
          <el-col :span="19">{{ param.containerFilter[packingInfo.containerClassify] }}</el-col>
        </el-row>
        <el-row class="marginTop10"> 
          <el-col :span="5" class="text-right"> {{ packingInfo.orderType==5 ? '客户：':'客户：' }} </el-col>
          <el-col :span="19">{{ packingInfo.agentName }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">租箱订单：</el-col>
          <el-col :offset="5" :span="19">
            <el-table :data="rentOrderList">
              <el-table-column prop="orderNo" label="订单号" align="center"/>
              <el-table-column label="预计提箱日期" align="center">
                <template #default="scope">{{ formatDate(scope.row.planPickupDate, 2) }} </template>
              </el-table-column>
              <el-table-column label="下单日期" align="center">
                <template #default="scope"> {{ formatDate(scope.row.createTime, 2) }} </template>
              </el-table-column>
              <el-table-column label="联系人" align="center">{{ packingInfo.agentUserName }}</el-table-column>
              <el-table-column label="联系电话" align="center">
                <template #default="scope">
                  <span v-if="packingInfo.agentUserAreaCode">+{{ packingInfo.agentUserAreaCode }} </span>
                  {{ packingInfo.agentUserTel }}
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">放箱指令号：</el-col>
          <el-col :span="19">{{ packingInfo.instruction }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">提箱单有效范围：</el-col>
          <el-col :span="19">
            {{ formatDate(packingInfo.packingValidityPeriodStart, 2) }}
            ~
            {{ formatDate(packingInfo.packingValidityPeriodEnd, 2) }}
          </el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">箱型/箱量/箱况：</el-col>
          <el-col :span="19">
            <el-table :data="packingRecord">
              <el-table-column prop="boxType" label="箱型"> </el-table-column>
              <el-table-column prop="boxCondition" label="箱况"> </el-table-column>
              <el-table-column prop="boxQuantity" label="箱量" ></el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">箱号：</el-col>
          <el-col :span="19">
            <el-row >
              <template v-for="(item,index) in  containerNoInfo" :key="index">
                <el-col :span="6" style="border:1px solid #ccc;" class="text-center">{{item.containerNo}}</el-col>
              </template>
              
            </el-row>
          </el-col>
        </el-row>
        <el-row class="marginTop10" v-if="!isAgent">
          <el-col :span="5" class="text-right">成本价：</el-col>
          <el-col :span="19">{{ packingInfo.rentInCurrency == 'USD'?'$':'¥' }} {{ packingInfo.rentInPrice || '--'}}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">堆场名称：</el-col>
          <el-col :span="19">{{ packingInfo.yardName }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">堆场地址：</el-col>
          <el-col :span="19">{{ packingInfo.yardAddress }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">联系人：</el-col>
          <el-col :span="19">{{ packingInfo.yardContact }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">联系电话：</el-col>
          <el-col :span="19">+{{packingInfo.areaCode}}  {{ packingInfo.yardTel }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">邮箱：</el-col>
          <el-col :span="19">{{ packingInfo.yardEmail }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">堆场作业时间：</el-col>
          <el-col :span="19">{{ packingInfo.yardWorkTime }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">附件：</el-col>
          <el-col :span="19">
          <showFile :detailFileList="packingInfo.packingFileList"></showFile>  
          </el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">备注：</el-col>
          <el-col :span="19">{{ packingInfo.remark }}</el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">状态：</el-col>
          <el-col :span="19">{{ { 5: '已发放', 10: '已下载', 15: '提箱中', 20: '已完成' ,25: '已作废', 30: '已过期' }[packingInfo.status] }}</el-col>
        </el-row>
      </div>
      <div v-else>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">提箱单号：</el-col>
          <el-col :span="17">{{ packingInfo.packingNo }}</el-col>
        </el-row>
        <el-row  class="marginTop10">
          <el-col :span="5" class="text-right">提箱单类型：</el-col>
          <el-col :span="17">{{ param.containerFilter[packingInfo.containerClassify] }}</el-col>
        </el-row>
        <el-row  class="marginTop10">
          <el-col :span="5" class="text-right"> {{ packingInfo.orderType==5 ? '客户：':'客户：' }} </el-col>
          <el-col :span="19">{{ packingInfo.agentName }}</el-col>
        </el-row>
        <el-row class="marginTop10">
            <el-col :span="5" class="text-right">租箱订单：</el-col>
            <el-col :offset="5" :span="19">
              <el-table :data="rentOrderList">
                <el-table-column prop="orderNo" label="订单号" width="200" align="center"> </el-table-column>
                <el-table-column label="预计提箱日期" width="150" align="center">
                  <template #default="scope"> {{ formatDate(scope.row.planPickupDate, 2) || '--'}} </template>
                </el-table-column>
                <el-table-column label="下单日期"  align="center">
                  <template #default="scope"> {{ formatDate(scope.row.createTime, 2) || '--'}} </template>
                </el-table-column>
                <el-table-column label="联系人" align="center">{{ packingInfo.agentUserName }}</el-table-column>
                <el-table-column label="联系电话" align="center">
                  <template #default="scope">
                    <span v-if="packingInfo.agentUserAreaCode">+{{ packingInfo.agentUserAreaCode }} </span>
                    {{ packingInfo.agentUserTel }}
                  </template>
                </el-table-column>>
              </el-table>
            </el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">提箱单有效期范围：</el-col>
          <el-col :span="19">
            {{ formatDate(packingInfo.packingValidityPeriodStart, 2) }}
            ~
            {{ formatDate(packingInfo.packingValidityPeriodEnd, 2) }}
          </el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">箱型/箱量/箱况：</el-col>
          <el-col :offset="5" :span="19">
            <el-table :data="packingRecord">
              <el-table-column prop="boxType" label="箱型"> </el-table-column>
              <el-table-column prop="boxCondition" label="箱况"> </el-table-column>
              <el-table-column prop="boxQuantity" label="箱量"></el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="5" class="text-right">成本价：</el-col>
          <el-col :span="19">{{ packingInfo.rentInCurrency == 'USD'?'$':'¥' }} {{ packingInfo.rentInPrice || '--'}}</el-col>
        </el-row>
        <el-row class="marginTop10"> 
          <el-col :span="5" class="text-right">集装箱公司名称：</el-col>
          <el-col :span="19">{{ packingInfo.companyName }}</el-col>
        </el-row>
        <el-row class="marginTop10"> 
          <el-col :span="5" class="text-right">堆场名称：</el-col>
          <el-col :span="19">{{ packingInfo.yardName }}</el-col>
        </el-row>
        <el-row class="marginTop10"> 
          <el-col :span="5" class="text-right">提箱单：</el-col>
          <el-col :span="19">
          <showFile v-if="typeDrawer==1" :detailFileList="packingInfo.pdfFile"></showFile>
          <indexUpload v-else-if="typeDrawer==2" ref="packingRef1" :fileList="fileList1" :type="'pdf_jpg_png_zip'"/>
          <!-- <ImgUpload ref="addBoxFileRef" v-else-if="typeDrawer==2"  :urlList="packingInfo.pdfFile" :displayType="2" :fileSize="3" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="1" :drag="true"></ImgUpload> -->
          </el-col>
        </el-row>
        <el-row class="marginTop10"> 
          <el-col :span="5" class="text-right">附件：</el-col>
          <el-col :span="19">
          <showFile :detailFileList="packingInfo.packingFileList"></showFile>  
          </el-col>
        </el-row>
        <el-row class="marginTop10"> 
          <el-col :span="5" class="text-right">备注：</el-col>
          <el-col :span="19">{{ packingInfo.remark }}</el-col>
        </el-row>
        <el-row class="marginTop10"> 
          <el-col :span="5" class="text-right">状态：</el-col>
          <el-col :span="19">{{ {5: '已发放', 10: '已下载', 15: '提箱中', 20: '已完成',25: '已作废', 30: '已过期'  }[packingInfo.status] }}</el-col>
        </el-row>
      </div>
       <template #footer v-if="typeDrawer==2">
            <div class="dialog-footer" style="display: flex; justify-content: center;">
               <el-button type="primary" @click="fileClick">确定</el-button>
            </div>
         </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { formatDate,formatterNumberKo } from '@/utils'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import indexUpload from '@/components/upload/index.vue'
import ImgUpload from '@/components/upload/uploadFiles-Images'
import { getDetailTable, getBoxEastDetailTable, getPackingDetailData, addPackingDetail, deletePackingDetail,getboxDetailData } from '@/api/orderManage/packingDetail'
import { getTable, getBoxEastTable, getPackingData,callbackBoxList, addPacking, finishPacking, downloadPacking, cancelledPacking,orderBoxQty,updatePackingInfoPdfFile } from '@/api/orderManage/packing'
import { downloadIamge } from '@/utils/download'
import OwnBox from '@/views/components/packingList/ownBox';
import ExternalBox from '@/views/components/packingList/externalBox';
import showFile from '@/components/upload/showFile.vue'
import { computed, onActivated, onMounted, reactive, ref, watch,provide ,nextTick,inject} from 'vue';
import {Plus, Delete,Edit,Message,Search,Download,Upload,Refresh,UploadFilled,ChatLineSquare} from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
const isAgent=inject('isAgent') //当前等角色  true 货代角色  false 集装箱公司角色
const formData = inject('formData')

const param = reactive({
  pageNum: 1,
  pageSize: 10,
  orderType: '5',
  orderTypeFilter: { 5: '出租', 10: '回调', 15: '外调' },
  containerFilter: { 5: '自有', 15: '外调' ,null:"--"},
  orderTypeOptions: [
    { value: '5', label: '出租', },
    { value: '15', label: '外调', },
  ],
  //table
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提', },
    { value: '5', label: '全新', },
  ],
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  //开提箱单列表
  rentOrderTable: [{ orderNo: '', planPickupDate: '', createTime: '' }],
  rentBoxTable: [{ boxType: '', boxQuantity: '', boxCondition: '' }],
  selectTable: [{ orderNo: '', planPickupDate: '', createTime: '', boxType: '', boxQuantity: '', boxCondition: '' }],
  selectBoxTable: [{ containerNo: '', boxType: '', inDays: '', boxCondition: '' }],
  buildData:[],
  packingType: '15', // 提箱单种类 15：开外调提箱单 5：自有提箱单
  drawerPackingRecord:false,
  rentInCurrency:'CNY',
  rentInPrice:0,
  // tagName:""
});
const feeCurrencyList=ref([
  {
    value:'CNY',
    label:'¥'
  },
  {
    value:'USD',
    label:'$'
  },
])
const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'packingNo', colWidth: '120', title: '提箱单号', type: '<a>', command: 'showInfo', isCheck: true },
    // { key: 'orderList',colWidth: '120', key2: 'orderNo', title: '订单号', type: '/', isCheck: true },
    { key: 'containerClassify', colWidth: '100', title: '提箱单类型', type: 'filter', filter: { 5: '自有', 15: '外调' ,null:"--"}, isCheck: true },
    { key: 'outBoxCompanyName', colWidth: '120', title: '箱东', type: 'text', isCheck: true },
    { key: 'yardName',colWidth: '80', title: '堆场名称', type: 'text', isCheck: true },
    { key: 'boxType', colWidth: '60', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '60', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货',20:'混提' }, isCheck: true },
    { key: 'residuePackingDays', colWidth: '120', title: '剩余提箱天数', isTooltip: true, tooltip: "负数代表超期未提天数", type: 'days',  after: '天', isCheck: true },
    { key: 'totalQuantity', colWidth: '80', title: '总箱量', type: 'totalQuantity', isCheck: true },
    { key: 'packedQuantity', colWidth: '80', title: '已提箱量', type: 'totalQuantity', isCheck: true },
    { key: 'totalQuantity',key2: 'packedQuantity', colWidth: '80', title: '未提箱量', type: 'quantity', isCheck: true },
    { key: 'packingValidityPeriod', colWidth: '150', title: '提箱单有效期范围', type: 'rangeStatus', isCheck: true },
    { key: 'agentName', colWidth: '150', title: '客户', type: 'text', isCheck: true },
    // { key: 'agentUserName', colWidth: '80', title: '联系人', type: 'text', isCheck: true },
    // { key: 'agentUserTel',colWidth: '140', title: '联系电话', type: 'phoneNumber',areaCode:"agentUserAreaCode", isCheck: true },
    { key: 'packingStatus', colWidth: '70', title: '状态', type: 'statusTixiang',  isCheck: true },
    {
      key: 'operate',
      colWidth: '240',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // icon: 'Download',
          command: 'downloadFile',
          name: '下载',     
          isShow: (row: any) => {
             return JSON.parse(row.pdfFile)!='';
          },
        },
        {
          // icon: 'ChatLineSquare',
          command: 'showPackingRecord', //param.drawer3
          // content: '提箱记录',
          name: '查看',
        },
         {
          // icon: 'Plus',
          command: 'goAddPackingRecord', // addPacking
          // content: '添加记录',
          name:'新增',
          isShow: (row) => {
            return row.packingStatus <= 15;
          },
        },
        {
          command: 'activEdit',
          name: '编辑',
          isShow: (row: any) => {
             return row.packingStatus <20 && row.containerClassify==15  && !isAgent.value;
          },
        },
        {
          // icon: 'Refresh',
          command: 'drawerPackingOpen', //param.drawer3
          name: '过期重开',
          // content: '过期重开',
          isShow: (row) => {
            if(row.packingStatus==5 || row.packingStatus==10 || row.packingStatus==15){
              return row.residuePackingDays < 0 && !isAgent.value
            }
          },
        },
         {
          // icon: 'Refresh',
          command: 'endPacking',
          // content: '完成',
          name:'提完',
          isShow: (row) => {
            return row.packingStatus == 15 && isAgent.value;
          },
        },       
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: false, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});
//校验规则
const validatePlanPackingDate = (rule: any, value: any, callback: any) => {
  if (value > new Date(new Date().setHours(0, 0, 0, 0))) {
    return callback(new Error('提箱日期 须小于等于 今天'))
  }
  return callback()
}
const packingRecordFormRules = {
  cardNo: [
    // { required: true, trigger: "blur", message: "不能为空" },
    { pattern: /^[a-zA-Z0-9\u4e00-\u9fa5!-/:-@[-`{-~\p{S}]{0,10}$/, trigger: "blur", message: "请输入 文字/数字/符号 最长不超过10位" }
  ],
  containerNo: [
    { required: true, trigger: "change", message: "不能为空" },
    // { pattern: /\S+/, trigger: "change", message: "箱号不能包含空格" },
    { pattern: /^[A-Z]{3}U\d{7}$/,trigger: "change",message: "请输入正确格式的箱号(4位大写字母+7位数字)"}
  ],
  packingDate: [{ required: true, trigger: "blur", message: "不能为空" },
  { required: true, validator: validatePlanPackingDate, trigger: "blur" }
  ],
   rentInPrice: [
    { required: true, trigger: "change", message: "不能为空" },
  ],
  // imgList: [{ required: true, trigger: "change", message: "提箱附件 不能为空" }]
}
const typeList = computed(() => {
  const list = [
    { id: 0, name: '全部' },
    { id: 5, name: '已发放' },
    { id: 10, name: '已下载' },
    { id: 15, name: '提箱中' },
    { id: 20, name: '已完成' },
    { id: 30, name: '已过期' },
    // { id: 25, name: '已作废' },
  ]
  return list
})

const orderTypeval = ref('')
onMounted(() => {
  nextTick(() => {
    if(isAgent.value){
          orderTypeval.value = "5"
    }else{
           orderTypeval.value = "10"
    }
    getTableData()
    })

})
function handleTypeChange(val: any) {
  param.packingStatus = val
  getTableData()
}

/*货代 查询提箱单分页列表
* @param {String} packingNo 提箱单号
* @param {String} yardName 堆场名称
* @param {String} boxCondition 提箱标准 5-全新   10-次新  15-适货  20-混提 
* @param {String} status 提箱单状态  5-已发放 10-已下载 15-提箱中 20-已完成
*/
function getTableData() {
  // let data = {
  //   pageNum: param.pageNum,
  //   pageSize: param.pageSize,
  //   packingNo: param.packingNo,
  //   yardName: param.yardName,
  //   boxCondition: param.boxCase,
  //   status: param.status,
  //   orderType: orderTypeval.value,
  //   orderNo: param.orderNo,
  //   agentName: param.agentName,
  //   containerClassify: param.containerClassify || ""
  // }
  table.config.loading = true;
  // 获取列表数据
  callbackBoxList(formData.value.id).then((res: any) => {
    table.data = res.data;
    table.data.forEach((item: any) => {
      item.packingValidityPeriod = formatDate(item.packingValidityPeriodStart, 2) + ' ~ ' + formatDate(item.packingValidityPeriodEnd, 2)
    })
    // table.config.total = res.data.total;
  })
  table.config.loading = false;
}
function handleReSet() {
  param.packingNo = null
  param.yardName = null
  param.boxCase = null
  param.agentName = null
  param.orderType = '5'
  param.orderNo = null
  param.containerClassify=''
  getTableData()
}

const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  param.packingNoWarning = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
    param.packingNoWarning.push(item.packingNo)
  })
  return ids
})

//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//下载--------------- 
const downloadFile = (rowData: any) => {
  if (rowData.pdfFile) {
    let pdfFile = JSON.parse(rowData.pdfFile)
    pdfFile=pdfFile[0]
    if (!pdfFile.url) return ElMessage.error('未找到文件')
    downloadIamge(pdfFile.url,pdfFile.originalFileName || new Date(Date.now()+28800000).toISOString())
    downloadPacking(rowData.packingId)
  } else {
    console.log(rowData)
    ElMessage.error('未找到文件')
  }
}

const ownboxRef = ref()
const externboxlRef=ref()
//过期重开回显
const drawerPackingOpen = (row: any) => {
  ElMessageBox.confirm('您确定要将提箱单设置为“已过期”状态，并重新开具提箱单?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      param.buildData = []
      param.packingType = row.containerClassify // 5-自有箱 15-外调箱
      param.orderType = row.orderType  // 开提箱单 5：租箱 10：回调
      param.drawerPacking = true
      nextTick(() => {
        if(param.packingType=='5'){
          row.id=row.packingId
          ownboxRef.value.openBox(row)         
        }else if(param.packingType=='15'){
          externboxlRef.value.openBox(row)
        }
      })
    }).catch(() => { });
  
}
//查看提箱记录
const packingRecord = ref([])
const rentOrderList = ref([])
const rowData = ref({})
const showPackingRecord = (row: any) => {
  param.drawer3 = true
  rowData.value = row
  const data = {
    pageNum: 1,
    pageSize: 200,
    packingId: row.packingId
  }
  getBoxEastDetailTable(data).then((res: any) => { //jc 2024.9.9 getDetailTable 改 getBoxEastDetailTable
    let list = res.data.list
    list.forEach((item: any) => {
      item.boxCondition = boxConditionFilter(item.boxCondition)
      item.boxType = boxTypeFilter(item.boxType)
      item.packingDate = formatDate(item.packingDate, 2)
    })
    packingRecord.value = list
  })
}
//提完
const endPacking = (row: any) => {
  ElMessageBox.confirm('确定已提完？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    finishPacking(row.packingId).then((res: any) => {
      getTableData();
    })
  }).catch(() => { });
}
const singleTableRef =ref()
// 添加提箱记录
// const rowData = ref({})
const { proxy } = getCurrentInstance();
const packingRef = ref()
const goAddPackingRecord = async(row: any) => {
  rowData.value = row
  await orderBoxQty(row.packingId).then((res: any) => {
    res.data.forEach((item: any) => {
      item.waitPackingQuantity = item.totalQuantity - 0 - (item.packedQuantity - 0)
      item.orderTime = formatDate(item.orderTime, 2)
    })
    param.orderList = res.data
    param.drawerPackingRecord = true
    param.rentInCurrency = row.rentInCurrency
    param.rentInPrice = row.rentInPrice
    nextTick(() => {
      if(res.data.length==1){
        singleTableRef.value?.toggleRowSelection(res.data[0], true)
        param.orderId = res.data[0].orderId
        param.orderNoTes =res.data[0].orderNo
      }
    })
     
  }).catch((err: any) => {
    ElMessage.error('查询订单失败！')
  })
}
const handleSelectionChange = (val: any) => {
  if (val && val[0]) {
    param.orderId = val[0].orderId
    param.orderNoTes = val[0].orderNo
  }
}
const handleAddPackingRecord = () => {
  if (!param.orderNoTes) {
    return ElMessage.warning('请选择提箱订单')
  }
  let boxCondition = ""
  if(rowData.value.boxCondition == 20){
    boxCondition = param.boxCondition
  }else{
    boxCondition = rowData.value.boxCondition
  }
  proxy.$refs.packingRecordFormRef.validate(valid => {
    if (!valid) return
    const imgList = packingRef.value.fileList || []
    // if (imgList.length == 0) {
    //   return ElMessage.warning('请上传提箱附件')
    // }
    if(!param.orderId) return ElMessage.warning('请选择订单号')
    let data = {
      "orderId": param.orderId,
      "orderNo": param.orderNoTes,
      "packingId": rowData.value.packingId,
      // "containerId": boxInfo.value.id,
      // "containerNo": boxInfo.value.containerNo,
      "containerId":"",
      "containerNo": param.containerNo?.trim().toUpperCase(),
      "packingDate": param.packingDate,
      "detailFileList": JSON.stringify(imgList),
      "plateNumber":param.plateNumber,
      "boxCondition": boxCondition || "",
    }
    if(!isAgent.value){
      data.rentInPrice=param.rentInPrice
      data.rentInCurrency=param.rentInCurrency

    }
    addPackingDetail(data).then((res: any) => {
      getTableData()
      param.drawerPackingRecord = false
    })
  })
}
//查看提箱单详情
const packingInfo = ref({})
const containerNoInfo = ref([])
const typeDrawer=ref(1) //1详情 2编辑
const fileList1=ref([]) //附件默认
const packingRef1 = ref([])

//详情
const showInfo = (row: any) => {
  typeDrawer.value=1
  showInfoDeta(row)
};
//编辑
const activEdit = (row: any) => {
  typeDrawer.value=2
  showInfoDeta(row)
};
const showInfoDeta=(row)=>{
  if (!row.packingId) {
    return ElMessage({ message: '暂无提箱单id信息', type: 'error' })
  }
  getPackingData(row.packingId).then((res: any) => {
    let dataDati = res.data
   let data=JSON.parse(JSON.stringify(dataDati))

    packingInfo.value = data
    if(typeDrawer.value==2){
    //  packingInfo.value.pdfFile=JSON.parse(data.pdfFile)
     fileList1.value=JSON.parse(data.pdfFile)
    }
    packingRecord.value = [{ boxQuantity: data.totalQuantity, boxType: boxTypeFilter(res.data.boxType), boxCondition: boxConditionFilter(res.data.boxCondition), containerNoList: JSON.parse(data.containerNoList) }]
    rentOrderList.value = JSON.parse(data.orderList)
    containerNoInfo.value = JSON.parse(data.containerNoList)
  param.drawer2 = true;

  })
}
const infoClose=()=>{
  packingInfo.value={}
  param.drawer2 = false;
}
// 去开提箱单
const handlePacking = (type,val) => {
  param.buildData = []
  param.packingType = type // 5-自有箱 15-外调箱
  param.orderType = val  // 开提箱单 5：租箱 10：回调
  param.drawerPacking = true
}
const closeDialog = () => {
  param.drawerPacking = false
  getTableData();
}
const packingInfoStr = () => {
  return []
}
provide('packingInfo', packingInfoStr);
provide('config', {
      disable:false, // 订单选择弹窗 筛选项是否可选
      sources: "management", // 组件引用来源： internal-订单内开提箱单 ， management -提箱管理内开提箱单 
      orderType: orderTypeval.value, // 订单类型 5：租箱 10：回调箱 
  });



//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}


const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getBoxEastTable({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list  && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}
const addBoxFileRef = ref()
const fileClick=()=>{
    let pdfFile = packingRef1.value.resultList || []
  let data={
    id:packingInfo.value.id,
    //  pdfFile:JSON.stringify(addBoxFileRef.value.fileList)
     pdfFile:JSON.stringify(pdfFile)

  }
   updatePackingInfoPdfFile(data).then((res: any) => {
    if (res.code == "00000") {
      infoClose()
       if(typeDrawer.value==2){
        getTableData();
      }
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const updateSelectAll = (val) => {
  allId.value = val
}
const resetForm = ()=>{
   param.orderNoTes=null
  param.orderId=null
  proxy.$refs.packingRecordFormRef?.resetFields()
}
</script>

<style scoped>
.el-form-diy {
  padding: 10px;

  div {
    width: 100%;
  }
}
</style>
